﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 批量删除仓库命令处理器
    /// </summary>
    public class DeleteRangeWarehouseHandler : IRequestHandler<DeleteRangeWarehouseCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<Warehouse> _warehouseRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="warehouseRepository">仓库仓储接口</param>
        /// <param name="mapper">对象映射器</param>
        public DeleteRangeWarehouseHandler(IBaseRespository<Warehouse> warehouseRepository, IMapper mapper)
        {
            _warehouseRepository = warehouseRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理删除仓库命令
        /// </summary>
        /// <param name="request">删除仓库命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含操作结果的ApiResult</returns>
        public async Task<ApiResult<int>> Handle(DeleteRangeWarehouseCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID获取仓库数据
                var warehouses = await _warehouseRepository.GetRangeAsync(request.Ids);
                if (!warehouses.Any())
                {
                    return new ApiResult<int>
                    {
                        Msg = "未找到指定的仓库",
                        Code = ApiEnum.Failed
                    };
                }

                // 执行批量软删除
                foreach (var warehouse in warehouses)
                {
                    warehouse.Isdel = true;
                }
                await _warehouseRepository.UpdateRange(warehouses);

                // 返回成功结果
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "批量删除成功",
                    Data = warehouses.Count()
                };
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"删除仓库时发生错误: {ex.Message}"
                };
            }
        }
    }
}
